'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';

const RegisterPage = () => {
  const router = useRouter();
  const [registerEmail, setRegisterEmail] = useState('');
  const [registerUsername, setRegisterUsername] = useState('');
  const [registerPassword, setRegisterPassword] = useState('');
  const [registerPasswordConfirm, setRegisterPasswordConfirm] = useState('');
  const [registerError, setRegisterError] = useState('');

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setRegisterError('');

    // 校验用户名
    const usernameRegex = /^[a-zA-Z0-9]{3,150}$/;
    if (!usernameRegex.test(registerUsername)) {
      setRegisterError('用户名必须是字母和数字组成，长度在 3 到 150 之间。');
      return;
    }

    // 校验邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(registerEmail)) {
      setRegisterError('邮箱格式不正确。');
      return;
    }

    // 校验密码长度
    if (registerPassword.length < 8 || registerPassword.length > 72) {
      setRegisterError('密码长度必须在 8 到 72 之间。');
      return;
    }

    // 校验确认密码
    if (registerPassword !== registerPasswordConfirm) {
      setRegisterError('密码和确认密码不匹配。');
      return;
    }

    try {
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/collections/users/records`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: registerUsername,
          password: registerPassword,
          passwordConfirm: registerPasswordConfirm,
          email: registerEmail,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        // 处理后端返回的错误信息
        if (data.code === 400 && data.data.username) {
          setRegisterError(data.data.username.message);
        } else {
          throw new Error(data.message || '注册失败');
        }
      }

      alert('注册成功！');
      router.push('/login'); // 注册成功后跳转回登录页
    } catch (err) {
      setRegisterError((err as Error).message);
    }
  };

  return (
    <div className="flex flex-col items-center justify-center h-screen">
      <h2 className="text-2xl font-bold mb-4">注册</h2>
      <form onSubmit={handleRegister} className="flex flex-col space-y-4">
        <input
          type="text"
          placeholder="用户名"
          value={registerUsername}
          onChange={(e) => setRegisterUsername(e.target.value)}
          required
          className="border p-2 rounded"
        />
        <input
          type="email"
          placeholder="邮箱"
          value={registerEmail}
          onChange={(e) => setRegisterEmail(e.target.value)}
          required
          className="border p-2 rounded"
        />
        <input
          type="password"
          placeholder="密码"
          value={registerPassword}
          onChange={(e) => setRegisterPassword(e.target.value)}
          required
          className="border p-2 rounded"
        />
        <input
          type="password"
          placeholder="确认密码"
          value={registerPasswordConfirm}
          onChange={(e) => setRegisterPasswordConfirm(e.target.value)}
          required
          className="border p-2 rounded"
        />
        {registerError && <p className="text-red-500">{registerError}</p>}
        <button
          type="submit"
          className="bg-green-500 text-white p-2 rounded"
        >
          注册
        </button>
      </form>
    </div>
  );
};

export default RegisterPage; 